import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
import routes from "./routes";
Vue.use(VueRouter);

let originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (localtion, resolve, reject) {
  if (resolve === undefined && reject === undefined) {
    // 如果成功回调和失败回调都没有
    // originPush() 不能直接调用，不然this指向会出问题
    return originPush.call(this, localtion).catch(() => {});
  } else {
    return originPush.call(this, localtion, resolve, reject);
  }
};
let originReplace = VueRouter.prototype.push;

VueRouter.prototype.replace = function (localtion, resolve, reject) {
  if (resolve === undefined && reject === undefined) {
    // 如果成功回调和失败回调都没有
    // originPush() 不能直接调用，不然this指向会出问题
    return originReplace.call(this, localtion).catch(() => {});
  } else {
    return originReplace.call(this, localtion, resolve, reject);
  }
};
const router = new VueRouter({
  routes,
});
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token;
  let userInfo = store.state.user.userInfo;
  if (token) {
    if (to.path === "/login") {
      // 如果登录了还想去登录页面的话
      next("/");
    } else {
      // 登录后去了别的页面
      if (userInfo.name) {
        // 无条件放行
        next();
      } else {
        try {
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          next("/login");
        }
      }
    }
  } else {
    //没登录
    next();
  }
});
export default router;
